package com.starsoft.trade.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.starsoft.frame.base.bean.BaseAcount;
import com.starsoft.frame.util.DateUtil;
import com.starsoft.frame.util.StringUtil;
import com.starsoft.smdc.bean.SmdcSecurity;
import com.starsoft.smdc.service.HolidayService;
import com.starsoft.smdc.service.SecurityService;
import com.starsoft.trade.bean.TradeAcount;
import com.starsoft.trade.dao.TradeAcountDao;

@Service
public class TradeAcountService {

	@Autowired
	TradeAcountDao tradeAcountDao;
	
	@Autowired
	HolidayService holidayService;
	
	@Autowired
	SecurityService securityService;
	
	public TradeAcount get(Integer acountId){
		return tradeAcountDao.get(acountId);
	}
	
	public List<BaseAcount> getRealAcountByUser(Integer userId){
		return tradeAcountDao.getRealAcountByUser(userId);
	}
	
	public List<TradeAcount> getAll(){
		return tradeAcountDao.getAll();
	}
	
	public void saveOrUpdate(TradeAcount tradeAcount){
		Date initDate = holidayService.getBusinessDay(tradeAcount.getInitDate(), true);
		if(DateUtil.isToday(initDate)|| initDate.after(new Date())){
			initDate = holidayService.getBusinessDay(new Date(), true);
		}
		tradeAcount.setInitDate(initDate);
		tradeAcountDao.saveOrUpdate(tradeAcount);
	}
	
	public void delete(Integer acountId){
		tradeAcountDao.delete(TradeAcount.class, acountId);
	}
	
	public boolean isAlive(TradeAcount tradeAcount, Date testDate) {
		testDate = DateUtil.floorTime(testDate);
		if (testDate.before(tradeAcount.getInitDate())) {
			return false;
		}
		Date endDate = tradeAcount.getEndDate();
		if (endDate != null && testDate.after(endDate)) {
			return false;
		}
		return true;
	}

	public SmdcSecurity getBaseIndex(Integer acountId){
		String cmpIndex = tradeAcountDao.get(acountId).getCmpIndex();
		if(StringUtil.isEmpty(cmpIndex)){
			cmpIndex = "000300.ss";
		}
		return securityService.get(cmpIndex);
	}
	
}
